<template>
    <div class="main-container" id="main-container">
        <div style="background: #fff; height: 100%" id="workshopCancelStocks">
            <PageTabelLayout>
                <template #pageHeader>
                    <div class="my-header" style="padding: 10px;box-sizing: border-box;" v-if="headerShow">
                        <a-form size="small" :model="searchData" auto-label-width layout="inline">
                            <a-form-item label="客户名称" label-col-flex="70px" :style="{width:'300px'}">
                                <a-input class="bacClass"  allow-clear v-model="searchData.customName" />
                            </a-form-item>
                            <a-form-item label="开单日期" label-col-flex="70px" :style="{width:'300px'}">
                                <a-range-picker  popup-container="html"  style="background-color:#fff;border:1px solid #ccc;"
                                    class="bacClass" v-model="itemStartAndEnd" allow-clear @change="changTime" />
                            </a-form-item>
                            <a-form-item label="退库单号" label-col-flex="70px" :style="{width:'300px'}">
                                <a-input class="bacClass"  allow-clear v-model="searchData.returnCode" />
                            </a-form-item>
                            <a-form-item label="退库类型" label-col-flex="70px" :style="{width:'300px'}">
                                <a-input class="bacClass"  allow-clear
                                    v-model="searchData.returnTypeName" />
                            </a-form-item>
                            <a-form-item label="布号" label-col-flex="70px" :style="{width:'300px'}">
                                <a-input class="bacClass"  allow-clear v-model="searchData.clothCode" />
                            </a-form-item>
                            <a-form-item label="品名" label-col-flex="70px" :style="{width:'300px'}">
                                <a-input class="bacClass"  allow-clear v-model="searchData.brandName" />
                            </a-form-item>
                        </a-form>
                    </div>
                    <div class="my-divisders">
                        <a-divider orientation="center">
                            <icon-double-up v-if="headerShow" @click="changHeadShow(false)" :strokeWidth="2" :size="18" />
                            <icon-double-down v-else @click="changHeadShow(true)" :strokeWidth="2" :size="18" />
                        </a-divider>
                    </div>
                    <div class="my-tool-bar" style="margin-bottom: 10px;">
                        <Toolbar :items="['查询', '新增', '审核', '删除', '导出']" @audit="audits" @select="selectHandler"
                            @add="addHandler" v-if="handlerState === 1" @export="exportHandler" @del="delHandler" />
                        <Toolbar :items="['查询', '导出']" @select="selectHandler" v-else @export="exportHandler" />
                    </div>
                </template>
                <template #pageTabel>
                    <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height:99%;width: 100%;z-index:999 ;">
                        <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
                            :suppressDragLeaveHidesColumns="true" rowSelection="multiple" @grid-ready="gridReady"
                            style="height:100%" class='ag-theme-alpine' :defaultColDef="defaultColDef"
                            :rowData="table.dataList" :columnDefs="cfsValue" :localeText="localeTextData"
                            @columnResized="onColumnResized" @columnMoved="onColumnMoved" />
                    </a-spin>
                </template>
                <paginationCopys :page-size-options="pagingList1" :total="total" show-total show-jumper show-page-size
                    @change="changePage" @page-size-change="changeSize" style="justify-content: center;margin-top: 10px;"
                    :page-size="pagination.pageSize" :current="pagination.page" />
            </PageTabelLayout>
            <a-drawer :drawer-style="{ zIndex: 9999 }" height="100%" unmountOnClose :visible="pageData.showAdd"
                :mask-closable="false" placement="bottom" @cancel="pageData.showAdd = false">
                <template #title>{{ pageData.sideTitle }}</template>
                <a-form ref="formRef" style="margin-top:20px" auto-label-width :model="dataForm" layout="inline"
                    size="small" :label-col-props="{ span: 10 }" :wrapper-col-props="{ span: 14 }">
                    <a-form-item label-col-flex="135px" label="退库单号" field="returnCode"
                        :rules="[{ required: true, message: '退库单号必填' }]" :validate-trigger="['change', 'blur']">
                        <a-input style="width:259px" v-model="dataForm.returnCode" allow-clear class="bacClass" />
                    </a-form-item>
                    <a-form-item label-col-flex="135px" label="仓库名称" field="warehouseName"
                        :rules="[{ required: true, message: '仓库名称必填' }]" :validate-trigger="['change', 'blur']">
                        <a-select popup-container="html"  class="bacClass" style="width:259px" v-model="dataForm.warehouseName" allow-clear
                            @click="whCSelecks" allow-search>
                            <a-option v-for="item in fhWhList" :value="item.id + '#' + item.warehouseName">
                                {{ item.warehouseName }}
                            </a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label-col-flex="135px" label="退货类型" field="returnTypeName"
                        :rules="[{ required: true, message: '退货类型必填' }]" :validate-trigger="['change', 'blur']">
                        <!-- <a-input v-model="dataForm.returnTypeName" allow-clear class="aInput" /> -->
                        <!-- <a-select popup-container="html"  style="width: 270px;" v-model="dataForm.retreatLibraryType">
                                <a-option />
                            </a-select> -->
                        <a-select popup-container="html"  class="bacClass" style="width:259px" v-model="dataForm.returnTypeName" allow-clear
                            @click="tkCSelecks" allow-search>
                            <a-option v-for="item in tkWhList" :value="item.id + '#' + item.stocksType">
                                {{ item.stocksType }}
                            </a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label-col-flex="135px" label="订单号" field="orderCode"
                        :rules="[{ required: true, message: '订单号必填' }]" :validate-trigger="['change', 'blur']">
                        <a-input allow-clear class="bacClass" style="width:273px" v-model="dataForm.orderCode" />
                    </a-form-item>
                    <a-form-item label-col-flex="135px" label="客户名称" field="customName"
                        :rules="[{ required: true, message: '客户名称必填' }]" :validate-trigger="['change', 'blur']">
                        <a-input allow-clear class="bacClass" style="width:259px" v-model="dataForm.customName" />
                    </a-form-item>
                    <a-form-item label-col-flex="135px" label="开单日期" field="returnDate"
                        :rules="[{ required: true, message: '开单日期必填' }]" :validate-trigger="['change', 'blur']">
                        <a-date-picker  popup-container="html"  v-model="dataForm.returnDate" allow-clear style="width:259px" class="bacClass" />
                    </a-form-item>
                    <a-form-item label-col-flex="135px" label="客户订单号" field="customOrderCode"
                        :rules="[{ required: true, message: '客户订单号必填' }]" :validate-trigger="['change', 'blur']">
                        <a-input allow-clear class="bacClass" style="width:245px" v-model="dataForm.customOrderCode" />
                    </a-form-item>
                    <a-form-item label-col-flex="135px" label="流转卡号" field="circulatCard"
                        :rules="[{ required: true, message: '流转卡号必填' }]" :validate-trigger="['change', 'blur']">
                        <a-input allow-clear class="bacClass" style="width:259px" v-model="dataForm.circulatCard" />
                    </a-form-item>
                    <a-form-item label-col-flex="135px" label="计件日期" field="reckonPieceDate"
                        :rules="[{ required: true, message: '计件日期必填' }]" :validate-trigger="['change', 'blur']">
                        <a-date-picker  popup-container="html"  allow-clear class="bacClass" style="width:259px"
                            v-model="dataForm.reckonPieceDate" />
                    </a-form-item>
                    <a-form-item label-col-flex="135px" label="班组" field="workTeam"
                        :rules="[{ required: true, message: '班组必填' }]" :validate-trigger="['change', 'blur']">
                        <a-input allow-clear class="bacClass" style="width:287px" v-model="dataForm.workTeam" />
                        <!-- <a-select popup-container="html"  style="width: 270px;" v-model="dataForm.team">
                                <a-option />
                            </a-select> -->
                    </a-form-item>
                    <a-form-item label-col-flex="135px" label="收费项" field="pollTeam"
                        :rules="[{ required: true, message: '收费项必填' }]" :validate-trigger="['change', 'blur']">
                        <!-- <a-input allow-clear class="aInput" v-model="dataForm.pollTeam" /> -->
                        <a-select popup-container="html"  class="bacClass" style="width:273px" v-model="dataForm.pollTeam" @click="sfCSelecks"
                            multiple>
                            <a-option v-for="item in sfxList">
                                {{ item.charges }}
                            </a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label-col-flex="135px" label="单价生成明细情况" field="priceStatus"
                        :rules="[{ required: true, message: '单价生成明细情况必填' }]" :validate-trigger="['change', 'blur']">
                        <a-input allow-clear class="bacClass" style="width:580px" v-model="dataForm.priceStatus" />
                    </a-form-item>
                    <a-form-item label-col-flex="135px" label="备注" field="remark">
                        <a-input allow-clear class="bacClass" style="width:676px" v-model="dataForm.remark" />
                    </a-form-item>
                    <a-form ref="formRef"
                        style="margin: 20px 0px;padding-top: 20px;padding-bottom: 20px;background: rgb(242, 247, 255);"
                        auto-label-width :model="dataForm" layout="inline" size="small" :label-col-props="{ span: 10 }"
                        :wrapper-col-props="{ span: 14 }">
                        <a-form-item label-col-flex="135px" label="费用类型" field="expenseTypeName"
                            :rules="[{ required: true, message: '费用类型必填' }]" :validate-trigger="['change', 'blur']">
                            <a-select popup-container="html"  class="bacClass" style="width:259px" v-model="dataForm.expenseTypeName">
                                <a-option>固定值</a-option>
                                <a-option>无费用</a-option>
                                <a-option>客户承担</a-option>
                                <a-option>染厂承担</a-option>
                                <a-option>织厂承担</a-option>
                            </a-select>
                        </a-form-item>
                        <a-form-item label-col-flex="135px" label="染色单价" field="dyePrice"
                            :rules="[{ required: true, message: '染色单价必填' }]" :validate-trigger="['change', 'blur']">
                            <a-input-number :min="0" :step="0.1" :precision="2" allow-clear class="bacClass"
                                style="width:259px" v-model="dataForm.dyePrice" />
                        </a-form-item>
                        <a-form-item label-col-flex="135px" label="耐氯提升单价" field="hoistPrice"
                            :rules="[{ required: true, message: '耐氯提升单价必填' }]" :validate-trigger="['change', 'blur']">
                            <a-input-number :min="0" :step="0.1" :precision="2" allow-clear class="bacClass"
                                style="width:230px" v-model="dataForm.hoistPrice" />
                        </a-form-item>
                        <a-form-item label-col-flex="135px" label="整理单价" field="sortPrice"
                            :rules="[{ required: true, message: '整理单价必填' }]" :validate-trigger="['change', 'blur']">
                            <a-input-number :min="0" :step="0.1" :precision="2" allow-clear class="bacClass"
                                style="width:259px" v-model="dataForm.sortPrice" />
                        </a-form-item>
                        <a-form-item label-col-flex="135px" label="胶袋单价" field="tapePrice"
                            :rules="[{ required: true, message: '胶袋单价必填' }]" :validate-trigger="['change', 'blur']">
                            <a-input-number :min="0" :step="0.1" :precision="2" allow-clear class="bacClass"
                                style="width:259px" v-model="dataForm.tapePrice" />
                        </a-form-item>
                        <a-form-item label-col-flex="135px" label="抗黄单价" field="yellowPrice"
                            :rules="[{ required: true, message: '抗黄单价必填' }]" :validate-trigger="['change', 'blur']">
                            <a-input-number :min="0" :step="0.1" :precision="2" allow-clear class="bacClass"
                                style="width:259px" v-model="dataForm.yellowPrice" />
                        </a-form-item>
                        <a-form-item label-col-flex="135px" label="纸管单价" field="paperPrice"
                            :rules="[{ required: true, message: '纸管单价必填' }]" :validate-trigger="['change', 'blur']">
                            <a-input allow-clear class="bacClass" style="width:259px" v-model="dataForm.paperPrice" />
                        </a-form-item>
                        <a-form-item label-col-flex="135px" label="单价构成" field="priceConstitute">
                            <a-input-number :min="0" :step="0.1" :precision="2" allow-clear class="bacClass"
                                style="width:271px" v-model="dataForm.priceConstitute" />
                        </a-form-item>
                        <a-form-item>
                            <a-checkbox v-model="dataForm.cylinderInState"> 进缸 </a-checkbox>
                            <a-checkbox v-model="dataForm.dyeFeesState"> 收染费 </a-checkbox>
                            <a-checkbox v-model="dataForm.pullStampState"> 拨印 </a-checkbox>
                            <a-checkbox v-model="dataForm.processRCState"> RC处理 </a-checkbox>
                            <a-checkbox v-model="dataForm.packState"> 打包 </a-checkbox>
                            <a-checkbox v-model="dataForm.firstClassState"> 一等品 </a-checkbox>
                            <a-checkbox v-model="dataForm.wetBrushState"> 湿刷 </a-checkbox>
                            <a-checkbox v-model="dataForm.processStickState"> 防粘处理 </a-checkbox>
                        </a-form-item>
                    </a-form>
                </a-form>
                <a-tabs   :lazy-load="true" default-active-key="0">
                    <!-- <template #extra>
                        <el-button type="success" :icon="iconText.CirclePlus"
                            @click="dataForm.retreatLibraryDetailedList.push({ ...detailItem })"
                            style="margin-bottom: 10px;background:#67c23a ;">新增</el-button>
                    </template> -->
                    <a-tab-pane key="0" title="退库明细">
                        <a-table size="small" :columns="createColumns" :data="dataForm.WorkshopReturnDetail"
                            :pagination="false" :bordered="{ cell: true }">
                            <template #action="{ rowIndex }">
                                <el-button type="danger" @click="dataForm.WorkshopReturnDetail.splice(rowIndex, 1)"
                                    link>删除</el-button>
                            </template>
                        </a-table>
                    </a-tab-pane>
                </a-tabs>
                <template #footer>
                    <a-button @click="pageData.showAdd = false">
                        关闭
                    </a-button>
                    <a-button type="primary" @click="saveHandler">
                        保存
                    </a-button>
                </template>
            </a-drawer>

        </div>
    </div>
</template>

<script lang="ts" setup>
import PageTabelLayout from '@/components/pageTabelLayout.vue';
import { reactive, ref, onMounted } from 'vue'
import emitter from "@/hooks/useEventBus";
import { useTableColumn } from '@/hooks/table'
import { WorkStocks, WSearchData } from '@/interface/workStocksInterface';

import { localeText } from '@/api/aggridZw'
import { post } from '@/api/http'
import { assTable } from '@/utils/assemblyLevelTable';
import { FormInstance, Message, Modal } from '@arco-design/web-vue';
import { usePagination, useTable } from '@/hooks/table';
import { workShopStocks } from '@/api/DyeingshopManagement/workshopCancelStocks'
import { CirclePlus } from '@element-plus/icons-vue';
import dayjs from 'dayjs';
import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'
import { pagingList } from "@/api/paging";

const workShopStocksApi = workShopStocks();
let headerShow = ref<boolean>(true);
let changHeadShow = (boolVal: boolean) => {
    headerShow.value = boolVal;
    emitter.emit('window-change');
};
onMounted(() => {
    pagination.page = 1;
    doRefresh();
});
let handlerState = ref<number>(1);
const selectHandler = () => {
    doRefresh();
};
const addHandler = () => {
    for (let i in dataForm) {
        dataForm[i] = ''
    }
    dataForm.reckonPieceDate = dayjs(Date.now()).format('YYYY-MM-DD')
    dataForm.returnDate = dayjs(Date.now()).format('YYYY-MM-DD')
    dataForm.cylinderInState = false
    dataForm.dyeFeesState = false
    dataForm.pullStampState = false
    dataForm.processRCState = false
    dataForm.packState = false
    dataForm.firstClassState = false
    dataForm.wetBrushState = false
    dataForm.processStickState = false
    formRef.value?.resetFields()
    post({
        url: 'aps/WorkshopReturn/getCodeGenerate ',
        data: {}
    }).then(({ data }) => {
        pageData.showAdd = true;
        dataForm.returnCode = data
        pageData.sideTitle = '新增';
    })
};
const formRef: any = ref<FormInstance>();
const saveHandler = () => {
    formRef.value?.validate().then(async (err) => {
        if (!err) {
            // console.log(dataForm)
            if (dataForm.id) {
                dataForm.cylinderInState = dataForm.cylinderInState ? 1 : 0
                dataForm.dyeFeesState = dataForm.dyeFeesState ? 1 : 0
                dataForm.pullStampState = dataForm.pullStampState ? 1 : 0
                dataForm.processRCState = dataForm.processRCState ? 1 : 0
                dataForm.packState = dataForm.packState ? 1 : 0
                dataForm.firstClassState = dataForm.firstClassState ? 1 : 0
                dataForm.wetBrushState = dataForm.wetBrushState ? 1 : 0
                dataForm.processStickState = dataForm.processStickState ? 1 : 0
                dataForm.warehouseId = Number(dataForm.warehouseName.split('#')[0])
                dataForm.warehouseName = dataForm.warehouseName.split('#')[1]
                dataForm.returnTypeId = Number(dataForm.returnTypeName.split('#')[0])
                dataForm.returnTypeName = dataForm.returnTypeName.split('#')[1]
                dataForm.pollTeam = dataForm.pollTeam.toString()
                await workShopStocksApi
                    .editStocks({ ...dataForm })
                    .then((res: any) => {
                        if (res.code === 200) {
                            formRef.value?.resetFields();
                            pageData.showAdd = false;
                            Message.success({
                                content: "修改成功",
                                duration: 5000,
                            });
                            doRefresh();

                        }
                        else {
                            Message.error({
                                content: res.message,
                                duration: 2000
                            });
                        }
                    })
                    .catch((res) => {
                        console.log(res);
                    });
            }
            else {
                dataForm.cylinderInState = dataForm.cylinderInState ? 1 : 0
                dataForm.dyeFeesState = dataForm.dyeFeesState ? 1 : 0
                dataForm.pullStampState = dataForm.pullStampState ? 1 : 0
                dataForm.processRCState = dataForm.processRCState ? 1 : 0
                dataForm.packState = dataForm.packState ? 1 : 0
                dataForm.firstClassState = dataForm.firstClassState ? 1 : 0
                dataForm.wetBrushState = dataForm.wetBrushState ? 1 : 0
                dataForm.processStickState = dataForm.processStickState ? 1 : 0
                dataForm.warehouseId = Number(dataForm.warehouseName.split('#')[0])
                dataForm.warehouseName = dataForm.warehouseName.split('#')[1]
                dataForm.returnTypeId = Number(dataForm.returnTypeName.split('#')[0])
                dataForm.returnTypeName = dataForm.returnTypeName.split('#')[1]
                dataForm.pollTeam = dataForm.pollTeam.toString()
                await workShopStocksApi
                    .addStocks({ ...dataForm })
                    .then((res: any) => {
                        if (res.code === 200) {
                            formRef.value?.resetFields();
                            pageData.showAdd = false;
                            Message.success({
                                content: "新增成功",
                                duration: 5000,
                            });
                            doRefresh();
                        } else {
                            Message.error({
                                content: res.message,
                                duration: 2000
                            });
                        }
                    })
                    .catch((res) => {
                        console.log(res);
                    });
            }
        }
    });
};


const dataForm: any = reactive({
    id: null,
    returnCode: '',
    warehouseName: '',
    warehouseId: null,
    returnTypeId: null,
    returnTypeName: '',
    orderCode: '',
    customName: '',
    returnDate: dayjs(Date.now()).format('YYYY-MM-DD'),
    customOrderCode: '',
    circulatCard: '',
    reckonPieceDate: dayjs(Date.now()).format('YYYY-MM-DD'),
    workTeam: '',
    pollTeam: '',
    priceStatus: '',
    remark: '',
    expenseTypeName: '',
    dyePrice: '',
    hoistPrice: '',
    sortPrice: '',
    tapePrice: '',
    yellowPrice: '',
    paperPrice: '',
    priceConstitute: '',
    WorkshopReturnDetail: [],
    cylinderInState: false,
    dyeFeesState: false,
    pullStampState: false,
    processRCState: false,
    packState: false,
    firstClassState: false,
    wetBrushState: false,
    processStickState: false,
});
const searchData: any = reactive({
    "beginDate": "",
    "endDate": "",
    "customName": "",
    "returnCode": "",
    "returnTypeName": "",
    "clothCode": "",
    "brandName": "",
});

const itemStartAndEnd = ref([])

const changTime = (data: any) => {
    console.log(data)
    if (data) {
        searchData.beginDate = data[0]
        searchData.endDate = data[1]
    } else {
        searchData.beginDate = ''
        searchData.endDate = ''
    }
}
const exportHandler = () => {
    // if (handlerState.value === 1) {
    //     emitter.emit('export-untreated');
    // } else {
    //     emitter.emit('export-processed');
    // }
    let selectList = gridOption.value.getSelectedRows();
    // console.log(selectList);
    if (selectList.length === 0) {
        Message.error('请勾选需要导出的数据')
        return
    } else {
        //导出数据
        let nowRow = table.dataList.filter(function (o) {
            return (gridOption.value.getSelectedRows().map((o: any) => { return o.id })).indexOf(o["id"]) !== -1;
        })
        assTable(cfsValue, nowRow, '车间退库信息');
    }
};
const changHandler = (e: number | string) => {
    handlerState.value = +e;
    selectHandler();
};
const pageData = reactive<({
    showAdd: boolean,
    pageLoading: boolean,
    sideTitle: string,
})>({
    showAdd: false,
    sideTitle: "新增",
    pageLoading: false
});
const createColumns = useTableColumn([
    {
        title: "客户名称",
        key: "customName",
        dataIndex: "customName",
        slotName: "customName",
        width: 150,
    },
    {
        title: "收料单号",
        key: "deliveryCode",
        dataIndex: "deliveryCode",
        slotName: "deliveryCode",
        width: 150,
    },
    {
        title: "送货单位",
        key: "deliveryDepartmentName",
        dataIndex: "deliveryDepartmentName",
        slotName: "deliveryDepartmentName",
        width: 150,
    },
    {
        title: "条形码",
        key: "clothfiyCode",
        dataIndex: "clothfiyCode",
        slotName: "clothfiyCode",
        width: 150,
    },
    {
        title: "织造序号",
        key: "weaveCode",
        dataIndex: "weaveCode",
        slotName: "weaveCode",
        width: 160,
    },
    {
        title: "布号",
        key: "clothCode",
        dataIndex: "clothCode",
        slotName: "clothCode",
        width: 160,
    },
    {
        title: "品名",
        key: "brandName",
        dataIndex: "brandName",
        slotName: "brandName",
        width: 150,
    },
    {
        title: "色称",
        key: "colorName",
        dataIndex: "colorName",
        slotName: "colorName",
        width: 150,
    },

    {
        title: "计划单号",
        key: "planOrderCode",
        dataIndex: "planOrderCode",
        slotName: "planOrderCode",
        width: 150,
    },
    // {
    //     title: "纱支",
    //     key: "yarnCount",
    //     dataIndex: "yarnCount",
    //     slotName: "yarnCount",//
    //     width: 150,
    // },
    {
        title: "门幅",
        key: "width",
        dataIndex: "width",
        slotName: "width",
        width: 150,
    },
    {
        title: "克重",
        key: "grawWeight",
        dataIndex: "grawWeight",
        slotName: "grawWeight",
        width: 150,
    },
    {
        title: "尺寸",
        key: "inch",
        dataIndex: "inch",
        slotName: "inch",
        width: 150,
    },
    {
        title: "匹数",
        key: "horseNum",
        dataIndex: "horseNum",
        slotName: "horseNum",
        width: 150,
    },
    {
        title: "纱批",
        key: "yarnBatch",
        dataIndex: "yarnBatch",
        slotName: "yarnBatch",
        width: 150,
    },
    // {
    //     title: "单价",
    //     key: "unitPrice",
    //     dataIndex: "unitPrice",
    //     slotName: "unitPrice",//
    //     width: 150,
    // },
    // {
    //     title: "金额",
    //     key: "amount",
    //     dataIndex: "amount",
    //     slotName: "amount",//
    //     width: 150,
    // },
    {
        title: "原库位",
        key: "orgStorageld",
        dataIndex: "orgStorageld",
        slotName: "orgStorageld",
        width: 150,
    },
    {
        title: "原托盘编号",
        key: "orgShelveld",
        dataIndex: "orgShelveld",
        slotName: "orgShelveld",
        width: 150,
    },
    {
        title: "新库位",
        key: "storageld",
        dataIndex: "storageld",
        slotName: "storageld",
        width: 150,
    },
    {
        title: "新托盘编号",
        key: "shelveld",
        dataIndex: "shelveld",
        slotName: "shelveld",
        width: 150,
    },
    // {
    //     title: "验后重量",
    //     key: "weight",
    //     dataIndex: "weight",
    //     slotName: "weight",
    //     width: 150,
    // },
    {
        title: "操作",
        key: "action",
        dataIndex: "action",
        slotName: "action",
        width: 150,
        fixed: "right",
    },
]);

const table = useTable();
const doRefresh = async () => {
    // workShopStocksApi
    pageData.pageLoading = true;
    // updateGridState01()
    await workShopStocksApi.getStocksList({
        page: pagination.page,
        size: pagination.pageSize,
        ...searchData
    }).then(({ data, code }) => {
        if (code === 200) {
            table.handleSuccess(data.list);
            gridOption.value.setRowData(data.list);
            total.value = data.total;
        }
    }).catch(console.log)
        .finally(() => {
            pageData.pageLoading = false;
        });
};
const editHandler = async (data: any) => {
    await workShopStocksApi.getStocksItem({ workshopReturnId: data.id }).then((res: any) => {
        // console.log(res);
        if (res.code === 200) {
            for (let key in data) {
                dataForm[key] = data[key];
            };
            dataForm.cylinderInState = dataForm.cylinderInState == 1 ? true : false
            dataForm.dyeFeesState = dataForm.dyeFeesState == 1 ? true : false
            dataForm.pullStampState = dataForm.pullStampState == 1 ? true : false
            dataForm.processRCState = dataForm.processRCState == 1 ? true : false
            dataForm.packState = dataForm.packState == 1 ? true : false
            dataForm.firstClassState = dataForm.firstClassState == 1 ? true : false
            dataForm.wetBrushState = dataForm.wetBrushState == 1 ? true : false
            dataForm.processStickState = dataForm.processStickState == 1 ? true : false
            dataForm.WorkshopReturnDetail = res.data
            whCSelecks()
            sfCSelecks()
            tkCSelecks()
            dataForm.returnTypeName = dataForm.returnTypeId + '#' + dataForm.returnTypeName
            dataForm.warehouseName = dataForm.warehouseId + '#' + dataForm.warehouseName
            dataForm.pollTeam = dataForm.pollTeam.split(',')
            pageData.showAdd = true;
            pageData.sideTitle = '编辑';
        } else {
            Message.error(res.message);
        }
    })
};

const delHandler = () => {
    let vals = gridOption.value.getSelectedRows().map((v: any) => { return v.id });
    if (vals.length > 0) {
        Modal.confirm({
            title: "提示",
            content: "确定要批量删除选中数据吗？",
            cancelText: "取消",
            okText: "删除",
            onOk: async () => {
                // const promises = vals.map((id: any) => {
                //     return workShopStocksApi.delStocks(id);
                // });
                await workShopStocksApi.delStocks(vals).then((res) => {
                    if (res.code === 200) {
                        Message.success("数据删除成功");
                        pagination.page = 1;
                        doRefresh();
                    } else {
                        Message.error("数据删除失败");
                    }
                });
                // Promise.all(promises).then((res: any) => {
                //     let resStatus = res.every((v: any) => v.code === 200)
                //     if (resStatus) {
                //         Message.success("数据删除成功");
                //         pagination.page = 1;
                //         doRefresh();
                //     }
                //     else {
                //         Message.error("数据删除失败");
                //     }
                // }).catch(error => {
                //     console.log(error)
                // });
            },
        });
    } else {
        Message.warning("请选择需要删除的数据");
    }
};

const setDelHandler = (id: any) => {
    Modal.confirm({
        title: "提示",
        content: "确定要删除选中数据吗？",
        cancelText: "取消",
        okText: "删除",
        onOk: async () => {
            await workShopStocksApi.delStocks([id]).then((res) => {
                if (res.code === 200) {
                    Message.success("数据删除成功");
                    pagination.page = 1;
                    doRefresh();
                } else {
                    Message.error("数据删除失败");
                }
            });
        },
    });
};



const pagination = usePagination(doRefresh);
//表格方面
const gridOption = ref();
const colState = ref()
const gridReady = (params: any) => {
    gridOption.value = params.api;
    colState.value = params.columnApi
    //调整表格自适应大小
}
const defaultColDef = {
    sortable: true,
    resizable: true,
    filter: true,
    width: 150
};
let cfsValue: any = [
    {
        headerName: '仓库名称',
        field: 'warehouseName',
    },
    {
        headerName: "退库类型",
        field: "returnTypeName",
    },
    {
        headerName: "收费类型",
        field: "expenseTypeName",
    },
    {
        headerName: "开单日期",
        field: "returnDate",
    },
    {
        headerName: "退库单号",
        field: "returnCode",
    },
    {
        headerName: "流转卡号",
        field: "circulatCard",
    },
    {
        headerName: "客户名称",
        field: "customName",
    },
    {
        headerName: "收货单号",
        field: "deliveryCode",
    },
    {
        headerName: "织造序号",
        field: "weaveCode",
    },
    {
        headerName: "布号",
        field: "clothCode",
    },
    {
        headerName: "品名",
        field: "brandName",
    },
    {
        headerName: "匹数",
        field: "horseNum",
    },
    {
        headerName: "色称",
        field: "colorName",
    },
    {
        headerName: "计划单号",
        field: "planOrderCode",
    },
    {
        headerName: "门幅",
        field: "width",
    },
    {
        headerName: "克重",
        field: "grawWeight",
    },
    {
        headerName: "纱批",
        field: "yarnBatch",
    },
    {
        headerName: "原库位",
        field: "orgSstorageName",
    },
    {
        headerName: "原托盘编码",
        field: "orgShelveCode",
    },
    {
        headerName: "新库位",
        field: "storageName",
    },
    {
        headerName: "新托盘编码",
        field: "shelveCode",
    },
    {
        headerName: "尺寸",
        field: "inch",
    },
    {
        headerName: '审核状态',
        field: 'auditState',
        pinned: 'right',
        width: 150,
        cellRenderer: {
            template: `
            <a-button v-if="states == 1" status="success">已审核</a-button>
            <a-button v-else="states == 0" type="dashed" status="success">未审核</a-button>
            `,
            setup(props: any) {
                return {
                    states: props.params.data.auditState
                }
            }
        },
        filterParams: {
            valueFormatter: function (params: any) {
                return params.value == '0'
                    ? '未审核'
                    : params.value == '1'
                        ? '已审核':''
            },
        }
    },
    {
        headerName: '操作',
        pinned: 'right',
        sortable: false,
        resizable: false,
        filter: false,
        width: 150,
        lockPosition: "right",
        cellRenderer: {
            template: `
                       <a-row align="center" justify="space-between"> 
                        <a-col :span="12">
                            <el-button style="color:#165dff;" link @click="a">修 改</el-button>
                        </a-col>
                        <a-col :span="12">
                            <el-button type="danger" link @click="b">删除</el-button>
                         </a-col>
                      </a-row> 
                    `,
            setup(props: any) {
                const a = () => {
                    editHandler(props.params.data);
                };
                const b = () => {
                    if (props.params.data.auditState == 1) {
                        Message.error('已审核不可删除')
                    } else {
                        setDelHandler(props.params.data.id);
                    }
                }
                return {
                    a,
                    b
                }
            }
        }
    },
];
let a = [{
    showRowGroup: 'hide_def',
    "headerName": "",
    "checkboxSelection": true,
    "headerCheckboxSelection": true,
    "pinned": "left",
    "width": 50,
    resizable: false,
    filter: false,
    sortable: false,
    minWidth: 50,
    maxWidth: 50,
    lockPosition: "left",
}]
cfsValue = a.concat(cfsValue);
const total = ref(10);
const changePage = (val: any) => {
    pagination.page = val
    doRefresh();
}
const changeSize = (val: any) => {
    pagination.pageSize = val
    doRefresh();
};
const localeTextData: any = ref(localeText);
let iconText: any = {
    CirclePlus
}

const audits = () => {
    let vals = gridOption.value.getSelectedRows().map((v: any) => {
        return {
            id: v.id,
            auditState: 1
        }
    });
    if (vals.length > 0) {
        Modal.confirm({
            title: "提示",
            content: "确定要审核选中数据吗？",
            cancelText: "取消",
            okText: "审核",
            onOk: async () => {
                await workShopStocksApi.auditStocks(vals).then((res) => {
                    if (res.code === 200) {
                        Message.success("数据审核成功");
                        pagination.page = 1;
                        doRefresh();
                    } else {
                        Message.error("数据审核失败");
                    }
                });
            },
        });
    } else {
        Message.warning("请选择需要审核的数据");
    }
}

const fhWhList: any = ref([])
const sfxList: any = ref([])
const tkWhList: any = ref([])

const whCSelecks = () => {
    post({
        url: 'dwWms/warehouse/getWarehouseByPara',
        data: {}
    }).then(({ data }) => {
        fhWhList.value = data
    })
}
const tkCSelecks = () => {
    post({
        url: 'dwWorkShop/stocksType/getList',
        data: {}
    }).then(({ data }) => {
        tkWhList.value = data
    })
}
const sfCSelecks = () => {
    post({
        url: 'pdm/chargeProject/select',
        data: {}
    }).then(({ data }) => {
        sfxList.value = data
    })
}

const pagingList1: any = ref(pagingList)
const { saveGridState: saveGridState01, updateGridState: updateGridState01 } = saveOrUpdateGridState01('workshopCancelStocks02', gridOption, colState, cfsValue)
const onColumnMoved = () => {
    saveGridState01()
}
const onColumnResized = () => {
    saveGridState01()
}
</script>

<style  scoped>
.fbg {
    background: rgb(242, 247, 255);
    margin: 200x 0px;
    padding: 20px;
}

.main-container {
    height: 100%;
}

.arco-drawer-header .arco-drawer-title {
    width: 100%;
}


.aInput {
    background: #fff;
    width: 270px;
    border: 1px solid #c9cdd3;
}

:deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
}

.aInputLine {
    border: 1px solid #c9cdd3;
    background: #fff;
}

:deep(.arco-scrollbar-track-direction-horizontal) {
    bottom: 20px;
    left: 0;
    box-sizing: border-box;
    width: 100%;
    height: 15px;
}

:deep(.arco-table .arco-table-element) {
    width: 100%;
    min-width: 100%;
    margin: 0;
    border-collapse: separate;
    border-spacing: 0;
    margin-bottom: 20px;
}
:deep(.arco-picker input){
    padding-left: 0 !important;
}
:deep(.arco-picker){
    padding-left: 0 !important;
}
:deep(.arco-picker-separator){
    padding: 0 !important;
}
</style>